<?php

namespace app\admin\controller\goods;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\goods\Goods as goodsModel;

/**
 * 商品搭配
 *
 * @icon fa fa-circle-o
 */
class Collocation extends Backend
{

    /**
     * Collocation模型对象
     * @var \app\admin\model\goods\Collocation
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\goods\Collocation;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index($ids = '')
    {
        //设置过滤方
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是 Selectpage，则转发到 Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->where('goods_id',$ids)
                ->order($sort, $order)
                ->paginate($limit);
            $result = ['total' => $list->total(), 'rows' => $list->items()];
            return json($result);

        }

        $this->assignconfig('good_id',$ids);
        return $this->view->fetch();

    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add($id = '')
    {

        $good_id = $this->request->param('good_id');

        if (false === $this->request->isPost()) {
            // 主商品id
            $this->view->assign('good_id',$good_id);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');

        $where = [];
        $where['goods_id']       = ['eq', $params['good_id']];
        $where['child_goods_id'] = ['eq', $params['id']];
        if (!$params['goods_name'])
        {
            $this->error('组合名不能为空');
        }
        if (array_key_exists('item',$params))
        {
            $params['child_goods_sku'] = $params['item'];
            $where['child_goods_sku'] = ['eq', $params['child_goods_sku']];
            unset($params['item']);
        }
        // 判断是否重复添加
        $goods_collocation = Db::name('goods_collocation')->where($where)->find();
        if ($goods_collocation)
        {
            $this->error('您已添加此类商品,无法重复操作');
        }

        if (empty($params['id']) || empty($good_id))
        {
            $this->error('商品不存在请从新选择您搭配的商品');
        }

        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        $params['goods_id'] = $params['good_id'];
        $params['child_goods_id'] = $params['id'];
        unset($params['good_id']);
        unset($params['id']);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['create_time'] = time();
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->assign('id',$this->request->param('id',1));
        $this->success();
    }

    /**
     * 选择搭配商品
     */
    public function selectgoods()
    {
        $this->model = new goodsModel();
// 当前是否为关联查询
        $this->relationSearch = true;
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->field(true)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $key => $row){
                if ($row['spec_type'] == 1){
                    $list[$key]['item'] = Db::name('goods_item')->where('goods_id',$row['id'])->select();
                }else{
                    $list[$key]['item'] = [];
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        return $this->view->fetch();
    }

}
